﻿using System;
using System.Collections.Generic;

namespace Plugins.FormicArch.Core
{
    
    /// <summary>
    /// 事件总线
    /// </summary>
    /// <typeparam name="T">模块事件</typeparam>
    public class EventBus<T>
    {
        private readonly Dictionary<Type, List<Action<IFAEvent>>> _handlers =
            new Dictionary<Type, List<Action<IFAEvent>>>();

        /// <summary>
        /// 订阅事件
        /// </summary>
        /// <param name="handler"></param>
        /// <typeparam name="TEvent"></typeparam>
        public void Subscribe<TEvent>(Action<TEvent> handler) where TEvent : IFAEvent
        {
            var eventType = typeof(TEvent);
            if (!_handlers.ContainsKey(eventType))
            {
                _handlers[eventType] = new List<Action<IFAEvent>>();
            }

            _handlers[eventType].Add(e => handler((TEvent)e));
        }

        /// <summary>
        /// 发布事件
        /// </summary>
        /// <param name="event"></param>
        /// <typeparam name="TEvent"></typeparam>
        public void Publish<TEvent>(TEvent @event) where TEvent : IFAEvent
        {
            var eventType = typeof(TEvent);
            if (_handlers.ContainsKey(eventType))
            {
                foreach (var handler in _handlers[eventType])
                {
                    handler(@event);
                }
            }
        }
    }
}